package com.situ.day13;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.junit.Test;

public class ReflectDemo {

	@Test
	public void testClass() throws ClassNotFoundException {
		// 1. Class.forName(类路径);
		Class clazz1 = Class.forName("com.situ.day13.Student");
		// 2. 类型.class
		Class clazz2 = Student.class;
		// 3. 对象.getClass();
		Student student = new Student();
		Class clazz3 = student.getClass();
		System.out.println(clazz1);
		System.out.println(clazz2);
		System.out.println(clazz3);
		System.out.println(clazz1 == clazz2);
		System.out.println(clazz2 == clazz3);
		System.out.println(clazz1 == clazz3);
	}

	@Test
	public void testConstructor() {
		Class clazz = Student.class;
		Constructor[] constructors = clazz.getDeclaredConstructors();
		for (Constructor constructor : constructors) {

			System.out.println(constructor);
			System.out.println(constructor.getModifiers());
			System.out.println(constructor.getName());
		}
	}

	@Test
	public void testConstructor2() throws NoSuchMethodException, SecurityException, InstantiationException,
			IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Class clazz = Student.class;
		// 得到制定参数的构造方法
		Constructor constructor = clazz.getDeclaredConstructor(String.class);
		System.out.println(constructor);
		// 加上之后就可以访问私有的构造方法
		constructor.setAccessible(true);
		// Student student = new Student("zhangsan");
		Student student = (Student) constructor.newInstance("zhangsan");
		System.out.println(student);
	}

	@Test
	public void testMethod() throws ClassNotFoundException, NoSuchMethodException, SecurityException,
			InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Class clazz = Class.forName("com.situ.day13.Student");
		// 得到无参构造方法
		Constructor constructor = clazz.getConstructor();
		// 调用newInstace实例化对象
		// Student student = new Student();
		Student student = (Student) constructor.newInstance();
		// student.setName("zhangsan");
		Method method = clazz.getMethod("setName", String.class);
		method.invoke(student, "zhangsan");
		System.out.println(student);
	}
}
